package com.fezs.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.fezs.common.context.BaseContextHandler;
import com.fezs.mybatis.model.AbstractEntity;
import com.fezs.mybatis.model.BaseEntity;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.Objects;

/**
 * 新增和修改字段填充类
 *
 * @author zhukai
 * @since 2022/8/18
 */
public class EntityFieldFillHandler implements MetaObjectHandler {

    public static final String CREATE_BY = "createBy";
    public static final String CREATE_TIME = "createTime";
    public static final String UPDATE_BY = "updateBy";
    public static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject == null) {
            return;
        }
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof AbstractEntity) {
            AbstractEntity abstractEntity = (AbstractEntity) originalObject;

            Date current = new Date();
            // 创建时间为空，则以当前时间为插入时间
            if (Objects.isNull(abstractEntity.getCreateTime())) {
                abstractEntity.setCreateTime(current);
            }
            // 更新时间为空，则以当前时间为更新时间
            if (Objects.isNull(abstractEntity.getUpdateTime())) {
                abstractEntity.setUpdateTime(current);
            }

        }
        if (originalObject instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) originalObject;

            Long userId = BaseContextHandler.getUserId();
            // 当前登录用户不为空，创建人为空，则当前登录用户为创建人
            if (Objects.isNull(baseEntity.getCreateBy())) {
                baseEntity.setCreateBy(userId);
            }
            // 当前登录用户不为空，更新人为空，则当前登录用户为更新人
            if (Objects.isNull(baseEntity.getUpdateBy())) {
                baseEntity.setUpdateBy(userId);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject == null) {
            return;
        }
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof AbstractEntity) {
            // 更新时间
            Object modifyTime = getFieldValByName(UPDATE_TIME, metaObject);
            setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
        if (originalObject instanceof BaseEntity) {
            // 当前登录用户不为空，更新人为空，则当前登录用户为更新人
            Object modifier = getFieldValByName(UPDATE_BY, metaObject);
            Long userId = BaseContextHandler.getUserId();
            if (Objects.isNull(modifier) || !userId.equals(modifier)) {
                setFieldValByName(UPDATE_BY, userId, metaObject);
            }
        }
    }

}
